package com.config;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileMonitor {
	private static final FileMonitor instance = new FileMonitor();

	private Timer timer;

	private Map timerEntries;

	private FileMonitor() {
		this.timerEntries = new HashMap();
		this.timer = new Timer(true);
	}

	public static FileMonitor getInstance() {
		return instance;
	}

	@SuppressWarnings("unchecked")
	public void addFileChangeListener(FileChangeListener listener,
			String filename, long period) throws IOException {
		this.removeFileChangeListener(filename);

		FileMonitorTask task = new FileMonitorTask(listener, filename);

		this.timerEntries.put(filename, task);
		this.timer.schedule(task, period, period);
	}

	public void removeFileChangeListener(String filename) {
		FileMonitorTask task = (FileMonitorTask) this.timerEntries
				.remove(filename);

		if (task != null) {
			task.cancel();
		}
	}

	private class FileMonitorTask extends TimerTask {
		private FileChangeListener listener;

		private String filename;

		private File monitoredFile;

		private long lastModified;

		public FileMonitorTask(FileChangeListener listener, String filename)
				throws IOException {
			this.listener = listener;
			this.filename = filename;

			this.monitoredFile = new File(filename);
			if (!this.monitoredFile.exists()) {
				return;
			}

			this.lastModified = this.monitoredFile.lastModified();

		}

		public void run() {
			long latestChange = this.monitoredFile.lastModified();
			if (this.lastModified != latestChange) {
				Date d = new Date(lastModified);
				System.out.println("������������"
						+ new SimpleDateFormat("yyyy��MM��dd HH:mm").format(d)
						+ "��������������");
				this.lastModified = latestChange;
				this.listener.fileChanged(this.filename);
			}
		}
	}
}
